class BookmarkManager {
    constructor() {
        this.bookmarks = this.loadBookmarks();
        this.categories = this.loadCategories();
        this.currentEditingBookmark = null;
        this.init();
    }

    init() {
        this.loadPageTitle();
        this.bindEvents();
        this.renderBookmarks();
        this.initSortable();
    }

    bindEvents() {
        // 添加按钮事件
        document.getElementById('addBtn').addEventListener('click', () => {
            this.showAddModal();
        });

        // 模态框事件
        document.getElementById('closeModal').addEventListener('click', () => {
            this.hideModal();
        });

        document.getElementById('cancelBtn').addEventListener('click', () => {
            this.hideModal();
        });

        // 表单提交事件
        document.getElementById('addBookmarkForm').addEventListener('submit', (e) => {
            e.preventDefault();
            this.saveBookmark();
        });

        // 点击模态框外部关闭
        document.getElementById('addModal').addEventListener('click', (e) => {
            if (e.target.id === 'addModal') {
                this.hideModal();
            }
        });

        // 右键菜单事件
        document.addEventListener('contextmenu', (e) => {
            const bookmarkCard = e.target.closest('.bookmark-card');
            if (bookmarkCard) {
                e.preventDefault();
                this.showContextMenu(e, bookmarkCard);
            } else {
                this.hideContextMenu();
            }
        });

        document.addEventListener('click', () => {
            this.hideContextMenu();
        });

        // 右键菜单项事件
        document.getElementById('editBookmark').addEventListener('click', () => {
            this.editBookmark();
        });

        document.getElementById('deleteBookmark').addEventListener('click', () => {
            this.deleteBookmark();
        });

        // 新分类输入事件
        document.getElementById('newCategory').addEventListener('input', (e) => {
            const select = document.getElementById('bookmarkCategory');
            if (e.target.value.trim()) {
                select.disabled = true;
            } else {
                select.disabled = false;
            }
        });

        // 刷新图标事件
        document.getElementById('refreshBtn').addEventListener('click', () => {
            this.refreshAllIcons();
        });

        // 导出导入事件
        document.getElementById('exportBtn').addEventListener('click', () => {
            this.exportData();
        });

        document.getElementById('importBtn').addEventListener('click', () => {
            document.getElementById('importFile').click();
        });

        document.getElementById('importFile').addEventListener('change', (e) => {
            this.importData(e.target.files[0]);
        });

        // 标题编辑事件
        const editTitleBtn = document.getElementById('editTitleBtn');
        if (editTitleBtn) {
            editTitleBtn.addEventListener('click', (e) => {
                e.preventDefault();
                e.stopPropagation();
                console.log('编辑按钮被点击');
                this.editPageTitle();
            });
        } else {
            console.error('找不到编辑标题按钮元素');
        }

        // 标题点击编辑事件
        const pageTitle = document.getElementById('pageTitle');
        if (pageTitle) {
            pageTitle.addEventListener('click', (e) => {
                e.preventDefault();
                e.stopPropagation();
                console.log('标题被点击');
                this.editPageTitle();
            });
        } else {
            console.error('找不到页面标题元素');
        }

        // 标题输入框失焦保存
        document.addEventListener('click', (e) => {
            const titleInput = document.querySelector('.title-input');
            if (titleInput && !titleInput.contains(e.target) && e.target !== titleInput) {
                this.saveTitleEdit();
            }
        });

        // 标题输入框回车保存
        document.addEventListener('keydown', (e) => {
            const titleInput = document.querySelector('.title-input');
            if (titleInput && e.target === titleInput) {
                if (e.key === 'Enter') {
                    e.preventDefault();
                    this.saveTitleEdit();
                } else if (e.key === 'Escape') {
                    e.preventDefault();
                    this.cancelTitleEdit();
                }
            }
        });
    }

    showAddModal(bookmark = null) {
        const modal = document.getElementById('addModal');
        const form = document.getElementById('addBookmarkForm');
        const title = modal.querySelector('h3');
        
        if (bookmark) {
            // 编辑模式
            title.textContent = '编辑网址';
            document.getElementById('bookmarkName').value = bookmark.name;
            document.getElementById('bookmarkUrl').value = bookmark.url;
            document.getElementById('bookmarkCategory').value = bookmark.category;
            this.currentEditingBookmark = bookmark;
        } else {
            // 添加模式
            title.textContent = '添加新网址';
            form.reset();
            this.currentEditingBookmark = null;
        }
        
        this.updateCategoryOptions();
        modal.style.display = 'block';
    }

    hideModal() {
        document.getElementById('addModal').style.display = 'none';
        document.getElementById('addBookmarkForm').reset();
        document.getElementById('bookmarkCategory').disabled = false;
        this.currentEditingBookmark = null;
    }

    async saveBookmark() {
        const name = document.getElementById('bookmarkName').value.trim();
        const url = document.getElementById('bookmarkUrl').value.trim();
        const categorySelect = document.getElementById('bookmarkCategory').value;
        const newCategory = document.getElementById('newCategory').value.trim();
        
        if (!name || !url) {
            alert('请填写完整信息');
            return;
        }

        // 确保URL格式正确
        let formattedUrl = url;
        if (!url.startsWith('http://') && !url.startsWith('https://')) {
            formattedUrl = 'https://' + url;
        }

        const category = newCategory || categorySelect;
        
        // 显示加载状态
        const saveBtn = document.getElementById('saveBtn');
        const originalText = saveBtn.textContent;
        saveBtn.innerHTML = '<span class="loading"></span> 保存中...';
        saveBtn.disabled = true;

        try {
            // 获取网站图标
            const icon = await this.getFavicon(formattedUrl);
            
            const bookmark = {
                id: this.currentEditingBookmark ? this.currentEditingBookmark.id : Date.now(),
                name,
                url: formattedUrl,
                category,
                icon,
                createdAt: this.currentEditingBookmark ? this.currentEditingBookmark.createdAt : new Date().toISOString()
            };

            if (this.currentEditingBookmark) {
                // 更新现有书签
                const index = this.bookmarks.findIndex(b => b.id === this.currentEditingBookmark.id);
                if (index !== -1) {
                    this.bookmarks[index] = bookmark;
                }
            } else {
                // 添加新书签
                this.bookmarks.push(bookmark);
            }

            // 添加新分类
            if (newCategory && !this.categories.includes(newCategory)) {
                this.categories.push(newCategory);
                this.saveCategories();
            }

            this.saveBookmarks();
            this.renderBookmarks();
            this.hideModal();
        } catch (error) {
            console.error('保存书签失败:', error);
            alert('保存失败，请检查网址是否正确');
        } finally {
            saveBtn.textContent = originalText;
            saveBtn.disabled = false;
        }
    }

    async getFavicon(url) {
        try {
            const domain = new URL(url).hostname;
            
            // 尝试多个图标获取方式
            const iconUrls = [
                `https://www.google.com/s2/favicons?domain=${domain}&sz=64`,
                `https://favicon.yandex.net/favicon/${domain}`,
                `https://${domain}/favicon.ico`,
                `https://api.faviconkit.com/${domain}/64`
            ];

            for (const iconUrl of iconUrls) {
                try {
                    const response = await fetch(iconUrl);
                    if (response.ok) {
                        // 检查内容类型是否为图片
                        const contentType = response.headers.get('content-type');
                        if (contentType && contentType.startsWith('image/')) {
                            // 检查内容长度，避免空图片或过小的图片
                            const contentLength = response.headers.get('content-length');
                            if (!contentLength || parseInt(contentLength) > 100) {
                                // 进一步验证图片是否可以加载
                                const isValidImage = await this.validateImage(iconUrl);
                                if (isValidImage) {
                                    return iconUrl;
                                }
                            }
                        }
                    }
                } catch (e) {
                    continue;
                }
            }
            
            // 如果都失败了，返回默认图标
            return null;
        } catch (error) {
            console.error('获取图标失败:', error);
            return null;
        }
    }

    // 验证图片是否可以正常加载
    validateImage(src) {
        return new Promise((resolve) => {
            const img = new Image();
            img.onload = () => {
                // 检查图片尺寸，避免1x1像素的占位图
                if (img.naturalWidth > 1 && img.naturalHeight > 1) {
                    resolve(true);
                } else {
                    resolve(false);
                }
            };
            img.onerror = () => resolve(false);
            img.src = src;
            
            // 设置超时，避免长时间等待
            setTimeout(() => resolve(false), 5000);
        });
    }

    renderBookmarks() {
        const categoriesContainer = document.getElementById('categories');
        categoriesContainer.innerHTML = '';

        // 按分类分组书签
        const bookmarksByCategory = this.groupBookmarksByCategory();
        
        // 确保至少有一个默认分类
        if (Object.keys(bookmarksByCategory).length === 0) {
            bookmarksByCategory['默认分类'] = [];
        }

        // 获取分类顺序
        const categoryOrder = this.loadCategoryOrder();
        const orderedCategories = this.sortCategoriesByOrder(Object.keys(bookmarksByCategory), categoryOrder);

        orderedCategories.forEach(category => {
            const bookmarks = bookmarksByCategory[category];
            const categoryDiv = this.createCategoryElement(category, bookmarks);
            categoriesContainer.appendChild(categoryDiv);
        });

        this.initSortable();
    }

    createCategoryElement(category, bookmarks) {
        const categoryDiv = document.createElement('div');
        categoryDiv.className = 'category';
        categoryDiv.dataset.category = category;

        // 创建分类标题容器
        const titleContainer = document.createElement('div');
        titleContainer.className = 'category-title-container';

        // 创建拖拽手柄
        const dragHandle = document.createElement('div');
        dragHandle.className = 'category-handle';
        dragHandle.innerHTML = '<i class="fas fa-grip-vertical"></i>';
        dragHandle.title = '长按拖动分类';

        const title = document.createElement('h2');
        title.textContent = category;

        titleContainer.appendChild(dragHandle);
        titleContainer.appendChild(title);

        const bookmarksContainer = document.createElement('div');
        bookmarksContainer.className = 'bookmarks';
        bookmarksContainer.id = `bookmarks-${category.replace(/\s+/g, '-')}`;

        bookmarks.forEach(bookmark => {
            const bookmarkElement = this.createBookmarkElement(bookmark);
            bookmarksContainer.appendChild(bookmarkElement);
        });

        categoryDiv.appendChild(titleContainer);
        categoryDiv.appendChild(bookmarksContainer);

        return categoryDiv;
    }

    createBookmarkElement(bookmark) {
        const bookmarkDiv = document.createElement('div');
        bookmarkDiv.className = 'bookmark-card';
        bookmarkDiv.dataset.id = bookmark.id;
        bookmarkDiv.dataset.category = bookmark.category;

        const icon = document.createElement('div');
        icon.className = 'bookmark-icon';
        
        if (bookmark.icon) {
            const img = document.createElement('img');
            img.src = bookmark.icon;
            img.alt = bookmark.name;
            img.onerror = () => {
                // 当缩略图加载失败时，使用默认的网页.png图片
                img.src = '网页.png';
                img.onerror = () => {
                    // 如果默认图片也加载失败，则显示图标
                    icon.innerHTML = '<i class="fas fa-globe"></i>';
                };
            };
            icon.appendChild(img);
        } else {
            // 没有图标时，直接使用默认的网页.png图片
            const img = document.createElement('img');
            img.src = '网页.png';
            img.alt = bookmark.name;
            img.onerror = () => {
                // 如果默认图片加载失败，则显示图标
                icon.innerHTML = '<i class="fas fa-globe"></i>';
            };
            icon.appendChild(img);
        }

        const title = document.createElement('div');
        title.className = 'bookmark-title';
        title.textContent = bookmark.name;

        const url = document.createElement('div');
        url.className = 'bookmark-url';
        url.textContent = new URL(bookmark.url).hostname;

        bookmarkDiv.appendChild(icon);
        bookmarkDiv.appendChild(title);
        bookmarkDiv.appendChild(url);

        // 点击事件
        bookmarkDiv.addEventListener('click', (e) => {
            if (e.button === 0) { // 左键点击
                window.open(bookmark.url, '_blank');
            }
        });

        return bookmarkDiv;
    }

    groupBookmarksByCategory() {
        const grouped = {};
        this.bookmarks.forEach(bookmark => {
            const category = bookmark.category || '默认分类';
            if (!grouped[category]) {
                grouped[category] = [];
            }
            grouped[category].push(bookmark);
        });
        return grouped;
    }

    initSortable() {
        // 书签拖拽排序
        const bookmarkContainers = document.querySelectorAll('.bookmarks');
        
        bookmarkContainers.forEach(container => {
            new Sortable(container, {
                group: 'bookmarks',
                animation: 150,
                ghostClass: 'sortable-ghost',
                chosenClass: 'sortable-chosen',
                dragClass: 'sortable-drag',
                onEnd: (evt) => {
                    this.handleDragEnd(evt);
                }
            });
        });

        // 分类拖拽排序
        const categoriesContainer = document.getElementById('categories');
        if (categoriesContainer) {
            new Sortable(categoriesContainer, {
                animation: 150,
                ghostClass: 'category-ghost',
                chosenClass: 'category-chosen',
                dragClass: 'category-drag',
                handle: '.category-handle', // 只能通过拖拽手柄拖动
                onEnd: (evt) => {
                    this.handleCategoryDragEnd(evt);
                }
            });
        }
    }

    handleDragEnd(evt) {
        const bookmarkId = parseInt(evt.item.dataset.id);
        const newCategory = evt.to.closest('.category').dataset.category;
        
        // 更新书签分类
        const bookmark = this.bookmarks.find(b => b.id === bookmarkId);
        if (bookmark) {
            bookmark.category = newCategory;
            this.saveBookmarks();
        }
    }

    handleCategoryDragEnd(evt) {
        // 获取新的分类顺序
        const categoryElements = document.querySelectorAll('.category');
        const newCategoryOrder = Array.from(categoryElements).map(el => el.dataset.category);
        
        // 保存分类顺序
        this.saveCategoryOrder(newCategoryOrder);
    }

    showContextMenu(event, bookmarkCard) {
        const contextMenu = document.getElementById('contextMenu');
        this.currentEditingBookmark = this.bookmarks.find(b => b.id == bookmarkCard.dataset.id);
        
        contextMenu.style.display = 'block';
        contextMenu.style.left = event.pageX + 'px';
        contextMenu.style.top = event.pageY + 'px';
    }

    hideContextMenu() {
        document.getElementById('contextMenu').style.display = 'none';
    }

    editBookmark() {
        if (this.currentEditingBookmark) {
            this.showAddModal(this.currentEditingBookmark);
        }
        this.hideContextMenu();
    }

    deleteBookmark() {
        if (this.currentEditingBookmark && confirm('确定要删除这个书签吗？')) {
            this.bookmarks = this.bookmarks.filter(b => b.id !== this.currentEditingBookmark.id);
            this.saveBookmarks();
            this.renderBookmarks();
        }
        this.hideContextMenu();
    }

    updateCategoryOptions() {
        const select = document.getElementById('bookmarkCategory');
        select.innerHTML = '';
        
        // 添加现有分类
        const existingCategories = [...new Set(this.bookmarks.map(b => b.category).filter(Boolean))];
        if (existingCategories.length === 0) {
            existingCategories.push('默认分类');
        }
        
        existingCategories.forEach(category => {
            const option = document.createElement('option');
            option.value = category;
            option.textContent = category;
            select.appendChild(option);
        });
    }

    // 本地存储方法
    saveBookmarks() {
        localStorage.setItem('bookmarks', JSON.stringify(this.bookmarks));
    }

    loadBookmarks() {
        const saved = localStorage.getItem('bookmarks');
        return saved ? JSON.parse(saved) : [];
    }

    saveCategories() {
        localStorage.setItem('categories', JSON.stringify(this.categories));
    }

    loadCategories() {
        const saved = localStorage.getItem('categories');
        return saved ? JSON.parse(saved) : ['默认分类'];
    }

    // 分类顺序相关方法
    saveCategoryOrder(categoryOrder) {
        localStorage.setItem('categoryOrder', JSON.stringify(categoryOrder));
    }

    loadCategoryOrder() {
        const saved = localStorage.getItem('categoryOrder');
        return saved ? JSON.parse(saved) : [];
    }

    sortCategoriesByOrder(categories, order) {
        // 按保存的顺序排序分类
        const orderedCategories = [];
        const unorderedCategories = [...categories];
        
        // 先添加有顺序的分类
        order.forEach(category => {
            const index = unorderedCategories.indexOf(category);
            if (index !== -1) {
                orderedCategories.push(category);
                unorderedCategories.splice(index, 1);
            }
        });
        
        // 再添加没有顺序的分类
        orderedCategories.push(...unorderedCategories);
        
        return orderedCategories;
    }

    // 标题编辑相关方法
    loadPageTitle() {
        const savedTitle = localStorage.getItem('pageTitle');
        if (savedTitle) {
            document.getElementById('pageTitle').textContent = savedTitle;
            document.title = savedTitle;
        }
    }

    savePageTitle(title) {
        localStorage.setItem('pageTitle', title);
        document.title = title;
    }

    editPageTitle() {
        console.log('editPageTitle方法被调用');
        const titleElement = document.getElementById('pageTitle');
        if (!titleElement) {
            console.error('找不到标题元素');
            return;
        }
        const currentTitle = titleElement.textContent;
        console.log('当前标题:', currentTitle);
        
        // 创建输入框
        const input = document.createElement('input');
        input.type = 'text';
        input.value = currentTitle;
        input.className = 'title-input';
        input.style.cssText = `
            background: rgba(255, 255, 255, 0.9);
            border: 2px solid #667eea;
            border-radius: 8px;
            padding: 8px 12px;
            font-size: 1.67rem;
            font-weight: 300;
            color: #333;
            outline: none;
            min-width: 200px;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
        `;
        
        // 替换标题元素
        titleElement.style.display = 'none';
        titleElement.parentNode.insertBefore(input, titleElement);
        
        // 选中文本并聚焦
        input.select();
        input.focus();
        
        // 保存原始标题用于取消操作
        this.originalTitle = currentTitle;
    }

    saveTitleEdit() {
        const input = document.querySelector('.title-input');
        if (!input) return;
        
        const newTitle = input.value.trim();
        if (newTitle && newTitle !== this.originalTitle) {
            const titleElement = document.getElementById('pageTitle');
            titleElement.textContent = newTitle;
            this.savePageTitle(newTitle);
        }
        
        this.finishTitleEdit();
    }

    cancelTitleEdit() {
        this.finishTitleEdit();
    }

    finishTitleEdit() {
        const input = document.querySelector('.title-input');
        const titleElement = document.getElementById('pageTitle');
        
        if (input) {
            input.remove();
        }
        
        titleElement.style.display = 'block';
        delete this.originalTitle;
    }

    // 数据导出导入方法
    exportData() {
        const data = {
            bookmarks: this.bookmarks,
            categories: this.categories,
            categoryOrder: this.loadCategoryOrder(),
            pageTitle: localStorage.getItem('pageTitle') || '我的导航页',
            exportDate: new Date().toISOString(),
            version: '1.0'
        };
        
        const dataStr = JSON.stringify(data, null, 2);
        const dataBlob = new Blob([dataStr], { type: 'application/json' });
        
        const link = document.createElement('a');
        link.href = URL.createObjectURL(dataBlob);
        link.download = `导航页数据_${new Date().toISOString().split('T')[0]}.json`;
        link.click();
        
        URL.revokeObjectURL(link.href);
        
        // 显示成功消息
        this.showMessage('数据导出成功！', 'success');
    }

    importData(file) {
        if (!file) return;
        
        const reader = new FileReader();
        reader.onload = (e) => {
            try {
                const data = JSON.parse(e.target.result);
                
                // 验证数据格式
                if (!data.bookmarks || !Array.isArray(data.bookmarks)) {
                    throw new Error('无效的数据格式');
                }
                
                // 确认导入
                if (confirm('导入数据将覆盖当前所有书签，确定要继续吗？')) {
                    this.bookmarks = data.bookmarks;
                    this.categories = data.categories || ['默认分类'];
                    
                    // 保存数据
                    this.saveBookmarks();
                    this.saveCategories();
                    
                    if (data.categoryOrder) {
                        this.saveCategoryOrder(data.categoryOrder);
                    }
                    
                    if (data.pageTitle) {
                        this.savePageTitle(data.pageTitle);
                        document.getElementById('pageTitle').textContent = data.pageTitle;
                    }
                    
                    // 重新渲染
                    this.renderBookmarks();
                    
                    this.showMessage('数据导入成功！', 'success');
                }
            } catch (error) {
                this.showMessage('导入失败：' + error.message, 'error');
            }
        };
        
        reader.readAsText(file);
    }

    async refreshAllIcons() {
        // 显示刷新开始的消息
        this.showMessage('正在刷新所有图标...', 'info');
        
        // 获取刷新按钮并添加旋转动画
        const refreshBtn = document.getElementById('refreshBtn');
        const refreshIcon = refreshBtn.querySelector('i');
        refreshIcon.style.animation = 'spin 1s linear infinite';
        refreshBtn.disabled = true;
        
        let updatedCount = 0;
        
        // 遍历所有书签，重新获取图标
        for (let bookmark of this.bookmarks) {
            try {
                const newIcon = await this.getFavicon(bookmark.url);
                if (newIcon && newIcon !== bookmark.icon) {
                    bookmark.icon = newIcon;
                    updatedCount++;
                } else if (!newIcon) {
                    // 如果获取失败，设置为null，这样会使用默认图片
                    bookmark.icon = null;
                }
            } catch (error) {
                console.error(`刷新书签 ${bookmark.name} 的图标失败:`, error);
                bookmark.icon = null;
            }
        }
        
        // 保存更新后的书签数据
        this.saveBookmarks();
        
        // 重新渲染书签
        this.renderBookmarks();
        
        // 恢复按钮状态
        refreshIcon.style.animation = '';
        refreshBtn.disabled = false;
        
        // 显示完成消息
        this.showMessage(`刷新完成！更新了 ${updatedCount} 个图标`, 'success');
    }

    showMessage(message, type = 'info') {
        // 创建消息提示
        const messageDiv = document.createElement('div');
        messageDiv.className = `message ${type}`;
        messageDiv.textContent = message;
        messageDiv.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 12px 20px;
            border-radius: 8px;
            color: white;
            font-weight: 500;
            z-index: 10000;
            animation: slideIn 0.3s ease;
            ${type === 'success' ? 'background: #4CAF50;' : ''}
            ${type === 'error' ? 'background: #f44336;' : ''}
            ${type === 'info' ? 'background: #2196F3;' : ''}
        `;
        
        document.body.appendChild(messageDiv);
        
        // 3秒后自动移除
        setTimeout(() => {
            messageDiv.style.animation = 'slideOut 0.3s ease';
            setTimeout(() => {
                if (messageDiv.parentNode) {
                    messageDiv.parentNode.removeChild(messageDiv);
                }
            }, 300);
        }, 3000);
    }
}

// 初始化应用
document.addEventListener('DOMContentLoaded', () => {
    new BookmarkManager();
});

// 键盘快捷键
document.addEventListener('keydown', (e) => {
    // Ctrl+N 或 Cmd+N 添加新书签
    if ((e.ctrlKey || e.metaKey) && e.key === 'n') {
        e.preventDefault();
        document.getElementById('addBtn').click();
    }
    
    // ESC 关闭模态框
    if (e.key === 'Escape') {
        const modal = document.getElementById('addModal');
        if (modal.style.display === 'block') {
            modal.style.display = 'none';
        }
    }
});